const path = require('path')
const util = require('util')
const chalk = require('chalk')
const fs = require('fs-extra')
const inquire = require('inquirer')
const ora = require('ora')
const downloadGitRepo = require('download-git-repo')
const {getNpmInfo} = require('./npm')
const requestSpinerLoading =  async (msg, fn)  =>{
    const spiner = ora(msg)
    spiner.start()
    try {
        const result = await fn
        spiner.succeed('succeed')
        return result
    }catch(e) {
        spiner.fail(e.message || 'request fail')
    }
    // spiner.succeed('delete succeed')
}
class Generator  {
    constructor (name,targetPath) {
        this.name = name
        this.targetPath = targetPath
        this.downloadGitRepo = util.promisify(downloadGitRepo)
    }
    async create() {
        console.log(this.name, this.targetPath)
        const name = await this.getTemplate()
       await this.download(name)
        // 4）模板使用提示
        console.log(`\r\nSuccessfully created project ${chalk.cyan(this.name)}`)
        console.log(`\r\n  cd ${chalk.cyan(this.name)}`)
    }
    async download (repo) {
        // 1）拼接下载地址
        const requestUrl = `willes/${repo}`;
        console.log(requestUrl, 'requestUrl')
        await requestSpinerLoading('正在下载模板...', this.downloadGitRepo(requestUrl, this.targetPath) )

    }
    async getTemplate() {
        const list = await requestSpinerLoading ('loading', getNpmInfo())
        const temps = list.map(item => item.name)
       const {templates} = await inquire.prompt([
            {
                name: 'templates',
                type: 'list',
                message: '选择模板',
                choices: temps

            }
        ])
        return templates
    }
}
module.exports = async function (name, options) {
    // 命令行执行的目录
    const dir = process.cwd();
    // 需要创建项目的地址
    const targetPath = path.join(dir, name)
    if(fs.existsSync(targetPath)) {
        // 强制覆盖
        if (options.force) {
         await fs.remove(targetPath)
        } else {
          // 如果存在 询问用户
           const {action} = await inquire.prompt([
                {
                    name: 'action',
                    type: 'list',
                    message: '项目文件夹已经存在',
                    choices: [{
                        name: 'OverWrite',
                        value: 'overwrite',
                    }, {
                        name: 'cancle',
                        value: false
                    }]
                }
            ])
            if (action) {
                await fs.remove(targetPath)
            }
        }
    }
    const generator = new Generator(name, targetPath)
    generator.create()
}
